package com.itheima.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import com.itheima.pojo.*;
import com.itheima.service.*;
import io.swagger.models.auth.In;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private UserService userService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private OrderDetailService orderDetailService;

    @PostMapping("submit")
    public R submit(@RequestBody Orders orders){

        Long currentId = BaseContext.getId();
        LambdaUpdateWrapper<ShoppingCart> wrapper=new LambdaUpdateWrapper<>();
        wrapper.eq(ShoppingCart::getUserId,currentId);
        List<ShoppingCart> list = shoppingCartService.list(wrapper);

        User user = userService.getById(currentId);
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
//        if (addressBook==null){
//            return R.error("地址信息有误！不能提交");
//        }
        AtomicInteger amount=new AtomicInteger(0);
        long orderId = IdWorker.getId();

        List<OrderDetail> orderDetails= list.stream().map((item)->{
            OrderDetail orderDetail=new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;

        }).collect(Collectors.toList());



        orders.setNumber(String.valueOf(orderId));
        orders.setId(orderId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        orders.setUserId(currentId);
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAmount(new BigDecimal(amount.get()));

        orders.setAddress((addressBook.getProvinceName()==null?"":addressBook.getProvinceName())
                +(addressBook.getCityName()==null?"":addressBook.getCityName())
                +(addressBook.getDistrictName()==null?"":addressBook.getDistrictName())
                +(addressBook.getDetail()==null?"":addressBook.getDetail()));
        orderService.save(orders);
        orderDetailService.saveBatch(orderDetails);
        shoppingCartService.remove(wrapper);;
        return R.success("1");
    }

@GetMapping("/page")
    public R page(Integer page,Integer pageSize){
    Page page1=new Page(page,pageSize);
        orderService.page(page1);
        return R.success(page1);

    }
@PutMapping
    public R update(@RequestBody Orders orders){

    Orders orders1 = orderService.getById(orders.getId());
    orders1.setStatus(orders.getStatus());
    orderService.updateById(orders1);
    return R.success("修改成功！");


}
//@GetMapping("/export")
//public R exportOrderList(HttpServletResponse response){
//
////orderDetailService.export(response);
//    List<OrderDetail> employeeList = orderDetailService.list();
//
//    ExcelWriterBuilder workBook = EasyExcel.write("D://develop//order.xlsx", OrderDetail.class);
//    // sheet方法参数： 工作表的顺序号（从0开始）或者工作表的名字
//    workBook.sheet("测试数据表").doWrite(employeeList);
//
//    return R.success("导出完成！");
//
//}


@GetMapping("/userPage")
public R userPage(Integer page,Integer pageSize){
        Page p=new Page(page,pageSize);
    Long userId = BaseContext.getId();
    LambdaQueryWrapper<Orders> wrapper=new LambdaQueryWrapper<>();
    wrapper.eq(Orders::getUserId,userId);
    Page page1 = orderService.page(p, wrapper);
    Page p2=new Page();


    List<Orders> records = page1.getRecords();

    List<OrdersDto> ordersDtoList=new ArrayList<>();


    for (Orders orders : records) {
        OrdersDto ordersDto=new OrdersDto();
        LambdaQueryWrapper<OrderDetail> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(OrderDetail::getOrderId,orders.getId());
        List<OrderDetail> list = orderDetailService.list(lambdaQueryWrapper);

        BeanUtils.copyProperties(orders,ordersDto);
        ordersDto.setOrderDetails(list);

        ordersDtoList.add(ordersDto);
    }

    long total = page1.getTotal();
    p2.setTotal(total);
    p2.setRecords(ordersDtoList);


    return R.success(p2);


}



}
